<template>
    <div id="account">

        <h3>客户类别</h3>
        <div>
            <el-select v-model="status" style="margin-left: 10px">
                <el-option>全部</el-option>
                <el-option :value="1" label="显示启用类别">显示启用类别</el-option>
                <el-option :value="2" label="显示禁用类别">显示禁用类别</el-option>
            </el-select>
            <el-button type="primary" style="margin-left: 10px" @click="searchPage(1, 5)">查询</el-button>
            <div style="float: right;">
                <el-button type="primary" @click="dialogFormVisible = true">新增</el-button>
                <el-button type="" @click="allUpdateSta()">禁用</el-button>
                <el-button type="primary" @click="allstartSta()">启用</el-button>
                <el-button type="" @click="reFlush()">刷新</el-button>
            </div>
        </div>
        <hr style="margin-top: 10px">
        <div class="account-content" style="margin-top: 10px;">
            <div>
                <el-table :data="treeData" style="width: 100%;margin-bottom: 20px;" row-key="typeId" border
                    default-expand-all :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
                    @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="55"></el-table-column>
                    <el-table-column prop="typeName" label="类别" width="200"></el-table-column>
                    <el-table-column prop="status" label="状态" width="150">
                        <template slot-scope="scope">
                            <el-switch v-model="scope.row.status" active-color="#66b1ff" inactive-color="#c1c1c1"
                                :active-value="1" :inactive-value="2"
                                @change="updateSta(scope.row.status, scope.row.typeId)"></el-switch>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="200">
                        <template slot-scope="scope">
                            <el-button @click="handleClick(scope.row.typeId)" type="text" size="small">删除</el-button>
                            <el-button @click="updateType(scope.row.typeId)" type="text" size="small">编辑</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>

        </div>

        <el-dialog width="400px" top="100px" title="新增客户类别" :visible.sync="dialogFormVisible">
            <AddCustomerType />
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="flush()">确 定</el-button>
            </div>
        </el-dialog>
        <el-dialog width="400px" top="100px" title="修改客户类别" :visible.sync="chooseType">
            <div>
                <table>
                    <tr>
                        <td>上级分类</td>
                        <td>
                            <el-button @click="choose = true">请选择分类</el-button>
                            <div v-show="choose">
                                <el-tree ref="tree" :data="treeData" :props="defaultProps" node-key="typeId"
                                    show-checkbox check-strictly @check-change="handleCheckChange">
                                </el-tree>
                            </div>
                        </td>
                    </tr>
                    <br>
                    <tr>
                        <td>类别</td>
                        <td><el-input v-model="type.typeName"></el-input></td>
                    </tr>
                    <br>
                    <tr>
                        <td></td>
                        <td><el-button style="margin-left: 170px" type="primary" @click="update()">修改</el-button></td>
                    </tr>
                </table>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="flush1()">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>

import AddAccount from './AddAccount.vue';
import AddCustomerType from './AddCustomerType.vue';
import UpdateCustomerType from './UpdateCustomerType.vue';

export default {
    name: 'Account',
    components: {
        AddAccount,
        AddCustomerType,
        UpdateCustomerType,
    },
    data() {
        return {
            pageInfo: "",
            treeData: [],
            dialogFormVisible: false,
            status: "",
            selectedTypeIds: [],
            chooseType: false,
            typeId: 0,
            typeName: "",
            choose: false,
            selectedTypeId: 0,
            defaultProps: {
                children: 'children',
                label: 'typeName'
            },
            type: {
                typeId: "",
                typeName: "",
                parentId: "",
                kind: "",
            }
        }

    },
    methods: {

        handleClick: function (typeId) {
            this.axios({
                url: "/info/type/delete",
                params: {
                    typeId: typeId,
                }
            }).then(rs => {
                console.log(rs)
                if (rs.data.info === "success") {
                    this.searchPage()
                } else {
                    alert("该用户下有子类，无法删除")
                }
            })
        },
        updateType: function (typeId) {
            this.typeId = typeId
            // alert(typeId)
            this.chooseType = true
            this.axios({
                url: "/info/type/selectById",
                params: {
                    typeId: typeId
                }
            }).then(rs => {
                this.type = rs.data.clear

                console.log(rs)
                console.log(this.type)
            })

        },
        update: function () {
            if (this.type.typeName === "") {
                alert("类别不能为空")
                return
            }
            alert(this.typeId)
            if (this.selectedTypeId === null) {
                this.selectedTypeId = 0
            }
            this.axios({
                url: "/info/type/update",
                params: {
                    typeId: this.typeId,
                    parentId: this.selectedTypeId,
                    typeName: this.type.typeName,
                    kind: "客户"
                }
            }).then(rs => {
                console.log(rs)
                if (rs.data.code === 200) {
                    alert("修改成功")
                } else {
                    alert("类别已存在")
                }
            })
        },
        handleCheckChange(node, checked) {
            // 如果取消勾选，则不进行操作
            if (checked) {
                // 取消勾选其他所有节点
                const allCheckedNodes = this.$refs.tree.getCheckedNodes();
                allCheckedNodes.forEach((checkedNode) => {
                    if (checkedNode.typeId !== node.typeId) {
                        this.$refs.tree.setChecked(checkedNode, false);
                    }
                });
                // 设置当前勾选节点的 typeId
                this.selectedTypeId = node.typeId;
                console.log(this.selectedTypeId)
            } else {
                // 如果节点被取消勾选，重置 selectedTypeId
                this.selectedTypeId = null;
            }
        },
        // 用于初始化或重置 selectedTypeId
        resetChecked() {
            this.selectedTypeId = null;
            this.$refs.tree.setCheckedKeys([]);
        },
        buildTree(data) {
            const tree = [];
            const map = {};

            // 将所有节点添加到map中，方便后续查找
            data.forEach(item => {
                map[item.typeId] = { ...item, children: [] };
            });

            // 构建树形结构
            data.forEach(item => {
                if (item.parentId === 0) {
                    tree.push(map[item.typeId]);
                } else {
                    if (map[item.parentId]) {
                        map[item.parentId].children.push(map[item.typeId]);
                    }
                }
            });

            return tree;
        },
        reFlush: function () {
            window.location.reload();
        },
        allstartSta: function () {
            if (!Array.isArray(this.selectedTypeIds) || this.selectedTypeIds.length === 0) {

                return;
            }
            const formData = new FormData();
            formData.append('list', JSON.stringify(this.selectedTypeIds));
            this.axios.post(
                "/info/type/allStartSta",

                formData

            ).then(rs => {
                this.searchPage()
                this.selectedTypeIds = []
            })
        },
        allUpdateSta: function () {
            if (!Array.isArray(this.selectedTypeIds) || this.selectedTypeIds.length === 0) {

                return;
            }
            const formData = new FormData();
            formData.append('list', JSON.stringify(this.selectedTypeIds));
            this.axios.post(
                "/info/type/allUpdateSta",

                formData

            ).then(rs => {
                this.searchPage()
                this.selectedTypeIds = []
            })
        },
        handleSelectionChange(val) {
            // val 是一个数组，包含了所有选中行的数据对象
            this.selectedTypeIds = val.map(item => item.typeId);
            console.log(this.selectedTypeIds)
        },
        updateSta: function (status, typeId) {
            // alert(status)
            // alert(typeId)
            this.axios({
                url: "/info/type/updateSta",
                params: {
                    status: status,
                    typeId: typeId
                }
            }).then(rs => {
                console.log(rs)
            })
        },
        flush: function () {
            this.dialogFormVisible = false
            this.searchPage()
        },
        flush1: function () {
            this.chooseType = false
            this.searchPage()
        },
        buildTree(data) {
            const tree = [];
            const map = {};

            // 将所有节点添加到map中，方便后续查找
            data.forEach(item => {
                map[item.typeId] = { ...item, children: [] };
            });

            // 构建树形结构
            data.forEach(item => {
                if (item.parentId === 0) {
                    tree.push(map[item.typeId]);
                } else {
                    if (map[item.parentId]) {
                        map[item.parentId].children.push(map[item.typeId]);
                    }
                }
            });

            return tree;
        },
        searchPage: function () {
            this.axios({
                url: "/info/type/typeByPage",
                params: {
                    kind: "客户",
                    status: this.status
                }
            }).then(rs => {
                console.log(rs.data)
                this.pageInfo = rs.data.pageInfo
                this.treeData = this.buildTree(this.pageInfo);
                console.log(this.treeData)
            })
        },

    },
    created: function () {
        this.searchPage()
        this.resetChecked()
    }
}
</script>

<style scoped>
#account {
    width: 100%;
    height: 100%;
}

.account-top {
    width: calc(100% -20px);
    height: 60px;
    /* background-color: pink; */
    line-height: 60px;
    padding-left: 20px;
    font-size: 13px;
}

.account-top h3 {
    display: inline-block;
    margin-right: 1000px;
}

.account-content {
    width: 100%;
    height: calc(100% - 60px);
    /* background-color: skyblue; */
}

.el-input,
.el-button {
    font-size: 13px;
}
</style>